from flask import Flask, request, jsonify, render_template
import pymysql

app = Flask(__name__,template_folder='')

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'db': 'jianghua',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

def get_db_connection():
    connection = pymysql.connect(**db_config)
    return connection

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
    data = request.get_json()
    date = data['date']
    weather = data['weather']
    mood = data['mood']
    event = data['event']

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diary (date, weather, mood, event) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, event))
        connection.commit()
    finally:
        connection.close()

    return jsonify({'message': 'Diary entry added successfully!'}), 201

@app.route('/history', methods=['GET'])
def history():
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM diary ORDER BY date DESC")
            entries = cursor.fetchall()
        return jsonify(entries)
    finally:
        connection.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)